package zap

import (
	"go.uber.org/zap"
	"go.uber.org/zap/zapcore"
	"os"
	"time"
)

var Logger *zap.SugaredLogger

func InitZap() {
	encoderConfig := zapcore.EncoderConfig{
		TimeKey:        "time",
		LevelKey:       "level",
		NameKey:        "logger",
		CallerKey:      "caller",
		MessageKey:     "msg",
		StacktraceKey:  "stacktrace",
		LineEnding:     zapcore.DefaultLineEnding,
		EncodeTime:     zapcore.TimeEncoderOfLayout("2006-01-02 15:04:05.000"), // ISO8601 UTC 时间格式
		EncodeDuration: zapcore.SecondsDurationEncoder,
		EncodeCaller:   zapcore.FullCallerEncoder, // 全路径编码器
		EncodeLevel: func(level zapcore.Level, enc zapcore.PrimitiveArrayEncoder) {
			var color string
			switch level {
			case zapcore.DebugLevel:
				color = "\x1b[34m" // 蓝色
			case zapcore.InfoLevel:
				color = "\x1b[32m" // 绿色
			case zapcore.WarnLevel:
				color = "\x1b[33m" // 黄色
			case zapcore.ErrorLevel:
				color = "\x1b[31m" // 红色
			case zapcore.FatalLevel:
				color = "\x1b[35m" // 紫色
			case zapcore.PanicLevel:
				color = "\x1b[36m" // 青色
			default:
				color = "\x1b[0m" // 默认无色
			}
			enc.AppendString(color + level.CapitalString() + "\x1b[0m") // 恢复默认颜色
		},
	}
	// 获取当前日期并格式化
	currentDate := time.Now().Format("2006-01-02")
	logFileName := "error_" + currentDate + ".log"

	// 创建文件写入器
	file, err := os.OpenFile(logFileName, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0666)
	if err != nil {
		panic(err)
	}

	fileCore := zapcore.NewCore(
		zapcore.NewJSONEncoder(encoderConfig),
		zapcore.AddSync(file),
		zap.ErrorLevel,
	)

	core := zapcore.NewCore(
		zapcore.NewConsoleEncoder(encoderConfig),
		zapcore.AddSync(os.Stdout),
		zap.InfoLevel,
	)

	multiCore := zapcore.NewTee(core, fileCore)

	Logger = zap.New(multiCore).Sugar()
}
